package cn.qyd.threadsignal;

import java.util.concurrent.Semaphore;

/**
 * @author 邱运铎
 * @date 2024-03-19 1:27
 */
public class SemaphoreDemo {
    private final Semaphore semaphore;

    public SemaphoreDemo(int limit) {
        this.semaphore = new Semaphore(limit);
    }

    public void useResource() {
        try {
            semaphore.acquire();
            System.out.println("资源开始使用了，当前线程： " + Thread.currentThread().getName());
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
            System.out.println("资源释放了，当前线程： " + Thread.currentThread().getName());
        }
    }
    public static void main(String[] args) {
        SemaphoreDemo demo = new SemaphoreDemo(3);

        for (int i = 0; i < 10; i++) {
            new Thread(demo::useResource).start();
        }
    }
}
